<?php

namespace Firegame\Model;
use Think\Model;

	class UsersModel extends Model {

    /**
     * [createUser 记录用户微信授权信息]
     * @param  [type] $data [授权返回数据]
     * @return [type]       [操作类型]
     */
    public function createUser($data) {
        if(empty($data)) { return array();}
        $openId = isset($data['openid']) ? $data['openid'] : '';
        $nickname = isset($data['nickname']) ? $data['nickname'] : '';
        $avatar = isset($data['avatar']) ? $data['avatar'] : '';

        $dataArr = array(
            'openid'=>$openId,
            'nickname'=>$nickname,
            'avatar'=>$avatar,
            //'status'=>2
        );


        // if(empty($data['uid'])) {
            $map['openid'] = $openId;
        // }else {
        // 	$map['id'] = $data['uid'];
        // }

        $users = M('users')->where($map)->find();

        if(empty($users)){
            $dataArr['create_time'] = time();
            $ret = M('users')->add($dataArr);
        // 更改则更新用户信息
        }else {
            $dataArr['update_time'] = time();
            $ret = M('users')->where($map)->save($dataArr);
        }

        if($ret) {
            $users = M('users')->where($map)->find();
            $uid = session('uid',$users['id']);
            $this->loginLog($users['id']);
        }

        return $users;
    }


		/**
     * 用户每日登陆记录
     */
    public function loginLog($uid) {
        $date = date('Y-m-d');
        $map['uid'] = $uid;
        $map['create_time'] = $date;
        $ret = M('users_sign_log')->where($map)->find();
        if(empty($ret)) {
            $data = array('uid'=>$uid,'create_time'=>$date);
            $res = M('users_sign_log')->add($data);
            if(empty($res)) {
            	Log::write('每日登陆记录日志失败','WARN');
            }
            if($res) {
            	$contion['id'] = $uid;
            	$ret2 = M('users')->where($contion)->setInc('sign_num',1);
            	if(empty($ret2)) {
            		Log::write('修改用户每日登陆次数失败','WARN');
            	}

            }
        }
    }


	}
?>